/**
 * 
 */
package swt.commons;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.Serializable;
import java.util.Properties;
import java.util.logging.Logger;

/**
 * SystemConfig
 */
public class ResourceUtil implements Serializable {

	/**
	 * serialVersionUID
	 */
	private static final long serialVersionUID = 6125460704673772961L;

	private static Logger log = LogUtil.getLogger();
	
	private static ResourceUtil resources;
	
	private Properties props;
	
	private String resourceFile;
	
	/**
	 * getInstance
	 * @return SystemResources
	 */
	public static ResourceUtil getInstance(){
		if (Utils.isNullEmpty(resources)){
			try {
				File f = new File(Const.resourceDir);
				if (!f.exists()){
					f.mkdir();
				}
				String resourceFile = Const.resourceDir + Const.resourceFile;
				resources = readSystemResource(resourceFile);
			} 
			catch (Exception e) {
				log.severe("ResourceUtil getInstance Exception");
				e.printStackTrace();
			}
		}
		return resources;
	}
	
    /**
	 * read language resource
	 */
    private static ResourceUtil readSystemResource(String file)
			throws IOException {
		
    	ResourceUtil resource = new ResourceUtil();
		File f = new File(file);
		if (!f.exists() || !f.isFile()){
			f.createNewFile();
		}
		FileInputStream fis = new FileInputStream(file);
		Properties prop = new Properties();
		prop.load(fis);
		fis.close();
		fis = null;
		
		resource.setProps(prop);
		resource.setResourceFile(file);
		return resource;
	}
    
	/**
	 * get text for control
	 * @param key
	 * @return String
	 */
	public String getProperty(String key){
		return resources.props.getProperty(key);
	}
	
	/**
	 * Add new property to Resource File
	 * @param key
	 * @param text
	 * @throws IOException
	 */
	public void setProperty(String key, String text) throws IOException {
		this.props.remove(key);
		this.props.setProperty(key, text);
	}
	
	/**
	 * Add new property to Resource File
	 * @param key
	 * @param text
	 * @throws IOException
	 */
	public void save() throws IOException {
		OutputStream out = new FileOutputStream(Const.resourceDir + Const.resourceFile, false);
		this.props.store(out, null);
		out.close();
		out = null;
	}

	/**
	 * @return the props
	 */
	public Properties getProps() {
		return props;
	}

	/**
	 * @param props the props to set
	 */
	public void setProps(Properties props) {
		this.props = props;
	}

	/**
	 * @return the resourceFile
	 */
	public String getResourceFile() {
		return resourceFile;
	}

	/**
	 * @param resourceFile the resourceFile to set
	 */
	public void setResourceFile(String resourceFile) {
		this.resourceFile = resourceFile;
	}
}
